package jnpf.service.impl;

import jnpf.base.ActionResult;
import jnpf.entity.*;
import jnpf.mapper.KnowFileMetadataMapper;
import jnpf.model.external.CreateMetadata;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.knowfilemange.*;
import jnpf.util.GeneraterSwapUtil;

import java.util.stream.Collectors;
import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.util.*;
import java.util.*;

/**
 *
 * knowFileMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-19
 */
@Service
public class KnowFileMetadataServiceImpl extends ServiceImpl<KnowFileMetadataMapper, KnowFileMetadataEntity> implements KnowFileMetadataService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DifyKnowService difyKnowService;


    //子表过滤方法
    @Override
    public QueryWrapper<KnowFileMetadataEntity> getChild(KnowFileMangePagination pagination, QueryWrapper<KnowFileMetadataEntity> knowFileMetadataQueryWrapper){
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    String ruleQueryJson = isPc?KnowFileMangeConstant.getColumnData():KnowFileMangeConstant.getAppColumnData();
    ColumnDataModel dataModel = JsonUtil.getJsonToBean(ruleQueryJson,ColumnDataModel.class);
    String ruleJson = isPc?JsonUtil.getObjectToString(dataModel.getRuleList()):JsonUtil.getObjectToString(dataModel.getRuleListApp());
        if(isPc){
        }
        return knowFileMetadataQueryWrapper;
    }

    @Override
    public List<KnowFileMetadataEntity> getKnowFileMetadataList(String mainId) {
        QueryWrapper<KnowFileMetadataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fileid", mainId);
        return this.list(queryWrapper);
    }

    @Override
    @Transactional
    public ActionResult updateKnowFileMetadataList(List<KnowFileMetadataEntity> metadataList) {
        if (metadataList == null || metadataList.isEmpty()) {
            return ActionResult.fail("数据列表为空");
        }

        // 获取第一个元素的fileid，假设所有元素的fileid相同
        String fileId = metadataList.get(0).getFileid();

        // 获取数据库中现有的数据
        QueryWrapper<KnowFileMetadataEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fileid", fileId);
        List<KnowFileMetadataEntity> existingList = this.list(queryWrapper);

        // 创建三个集合分别存储新增、更新和删除的数据
        List<KnowFileMetadataEntity> toAdd = new ArrayList<>();
        List<KnowFileMetadataEntity> toUpdate = new ArrayList<>();
        List<String> toDelete = new ArrayList<>();

        // 将现有数据放入Map方便查找
        Map<String, KnowFileMetadataEntity> existingMap = existingList.stream()
                .collect(Collectors.toMap(KnowFileMetadataEntity::getId, entity -> entity));

        // 处理传入的数据
        for (KnowFileMetadataEntity entity : metadataList) {
            if ("3".equals(entity.getHandle())) {
                // handle为3表示新增数据
                toAdd.add(entity);
            } else if ("1".equals(entity.getHandle()) && existingMap.containsKey(entity.getId())) {
                // handle为1且数据库中存在表示更新数据
                toUpdate.add(entity);
            } else if ("2".equals(entity.getHandle()) && existingMap.containsKey(entity.getId())) {
                // handle为2且数据库中存在表示删除数据
                toDelete.add(entity.getId());
            }

        }
        this.saveBatch(toAdd);

        //RAG创建元数据
        String ragdataid = metadataList.get(0).getRagfileid();
        StringBuilder metaBuilder = new StringBuilder("{");
        boolean isFirst = true;
        for (KnowFileMetadataEntity knowFileMetadataEntity : metadataList) {
            String type = knowFileMetadataEntity.getType();
            String value = knowFileMetadataEntity.getValue();
            String name = knowFileMetadataEntity.getName();
            if (!isFirst) {
                metaBuilder.append(",");
            }
            // 数字类型不加引号，其他类型加引号
            if ("2".equals(type)) {
                metaBuilder.append("\"").append(name).append("\": ").append(value);
            } else {
                metaBuilder.append("\"").append(name).append("\": \"").append(value).append("\"");
            }
            isFirst = false;
        }
        metaBuilder.append("}");
        String meta = metaBuilder.toString();
        CreateMetadata createMetadata = new CreateMetadata();
        createMetadata.setDoc_id(ragdataid);
        createMetadata.setMeta(meta);
        try {
            ActionResult metadata = difyKnowService.createMetadata(createMetadata);
            if (metadata.getCode() != 200) {
                return ActionResult.fail("RagFlow链接异常");
            }
        } catch (Exception e) {
            return ActionResult.fail("RagFlow链接异常");
        }

        if (!toUpdate.isEmpty()) {
            this.updateBatchById(toUpdate);
        }
        if (!toDelete.isEmpty()) {
            this.removeByIds(toDelete);
        }
        return ActionResult.success("数据更新成功");
    }


}
